from pandas import *
import pandas as pd
#import smartcharting
import matplotlib.pyplot as plt
#import twintowers
from datetime import date, tzinfo, timedelta, datetime

"""rng= date_range('4/15/2012', periods=1000, freq='h')
rng= rng[rng.hour < 16]
ts= Series(np.random.randn(len(rng)).cumsum(), rng)
fig= charting.Figure(1)
ts.fplot('no gaps')"""

#ps=[('HTHT','HMIN'),('CEA','ZNH'),('NTES','SOHU'),('CYOU','PWRD'),('CGA','YONG'),('GURE','SHI'),('OSN','SCOK'),('CAAS','SORL')]
#ps=[('HMIN','HTHT'),('ATHM','BITA')]
ps=[('ATHM','BITA')]

ind=1
figsize=(4,4)
currentday = date.today()
oneday = timedelta(days=1)
fdir = "c:\\Users\\Public\\_tt\\_data\\henry\\" # data directory
outputdir='C:\\_data\\spread\\'
sps=[]
for s1, s2 in ps:
    #twintowers.backtest([s1,s2],display=False)
    #if ind==1:
    #    fig= smartcharting.Figure(figsize[0],figsize[1])
    p1=pd.read_csv(fdir+s1+'.lst',index_col=0,parse_dates=True,dayfirst=True)
    p2=pd.read_csv(fdir+s2+'.lst',index_col=0,parse_dates=True,dayfirst=True)
    dff = p1-p2
    dff = dff.dropna()

    for i in range(140,0,-1):
      #d = timedelta(days=i)
      currentday = date.today() - timedelta(days=i)
      previousday = currentday - oneday
      str_previousday = str(previousday)
      str_currentday = str(currentday)
      qstr="('{prev}'<Datetime) & (Datetime<'{curr}')".format(prev=str_previousday,curr=str_currentday)
      print qstr
      df = dff.query(qstr)
      #currentday = previousday
      if len(df)==0:
          continue
      low=df.Low
      high=df.High

      spread=high.max()-low.min()
      sps.append(spread)
    """
      ax1 = plt.subplot(2,1,1)
      plt.title("low,high@{}@{}-{}@spread={}".format(str_previousday,s1,s2,spread))
      plt.setp(ax1.get_xticklabels(), visible=True)
      low.hist(bins=np.arange(low.min(),low.max(),(low.max()-low.min())/200),color='r',alpha=0.4)
      plt.setp(ax1.get_xticklabels(), visible=True)
      high.hist(bins=np.arange(high.min(),high.max(),(high.max()-high.min())/200),color='b',alpha=0.4)

      ax4 = plt.subplot(2,1,2)
      #plt.title("low,high@{}@{}-{}@spread={}".format(str_previousday,s1,s2,spread))
      plt.setp(ax4.get_xticklabels(), visible=True)
      low.plot(ax=ax4,style='-')
      high.plot(ax=ax4,style='-')
      pngfile='{s0}/{s1}-{s2}-{s3}.png'.format(s0=outputdir,s1=s1,s2=s2,s3=str_previousday)
      plt.savefig(pngfile)
      print "date={},spread={}".format(str_previousday,spread)
      #plt.show()
      plt.clf()
    """
    plt.subplot(2,1,1)
    plt.plot(sps)
    plt.subplot(2,1,2)
    #plt.hist(sps, bins=np.arange(min(sps),max(sps),(max(sps)-min(sps))/100),color='b',alpha=0.4)
    plt.hist(sps, 50)
    plt.show()
    sps=[]
"""
PWRD=pd.read_csv('F:\\uploaded\\PWRD.csv',index_col=0,parse_dates=True,dayfirst=True)
CYOU=pd.read_csv('F:\\uploaded\\CYOU.csv',index_col=0,parse_dates=True,dayfirst=True)

CYOU=pd.read_csv('F:\\uploaded\\CYOU.csv',index_col=0,parse_dates=True,dayfirst=True)
_3hk=pd.read_csv('F:\\uploaded\\3.HK.csv',index_col=0,parse_dates=True,dayfirst=True)
_4hk=pd.read_csv('F:\\uploaded\\4.HK.csv',index_col=0,parse_dates=True,dayfirst=True)

_sohu=pd.read_csv('F:\\uploaded\\sohu.csv',index_col=0,parse_dates=True,dayfirst=True)

fig= smartcharting.Figure(1)
#fig= henry_charting.Figure(1)
_ntes=pd.read_csv('F:\\uploaded\\ntes.csv',index_col=0,parse_dates=True,dayfirst=True)


s=PWRD-CYOU
c=s[['Close']].head(len(PWRD))
c.fplot(ls=':',marker='o',mintick=20, label='spread')
#c.fplot(ls=':', marker='o', label='spread')
plt.grid(True)

#ax.set_ylabel('y-label', fontsize=fontsize)
plt.tight_layout()


#PWRD[['Open','Close','Low','High']].fplot()
#CYOU[['Open','Close','Low','High']].fplot()

#ts1=PWRD[['Close']]
ts2=CYOU[['Close']]
ts3=_3hk[['Close']]
ts4=_4hk[['Close']]

#ts1.fplot('PWRD')
ts2.fplot('CYOU')
ts3.fplot('3.HK')
ts4.fplot('4.HK')

sohu=_sohu[['TYPE']]
ntes=_ntes[['TYPE']]

sohu.fplot('CYOU')
ntes.fplot('PWRD')

plt.show()
"""
